<?php

namespace App\Listeners\CallingCards;

use App\Events\CallingCards\OfficialRecordEvent;
use App\Library\Freeker\FreekerApi;
use App\Models\FeishuCallingCard\FeishuCallingCard;
use App\Models\FeishuCallingCard\FeishuCallingCardFranchiseeClue;
use App\Service\CallingCards\RegionalCodeService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;

class ClueSaveAndPushListener implements ShouldQueue
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param OfficialRecordEvent $event
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function handle(OfficialRecordEvent $event)
    {
        $invitorId = $event->invitorId;
        $salesName = '官网加盟填表';
        $remark    = mb_substr($event->remark, 0, 255);
        $card      = FeishuCallingCard::find($invitorId);
        if ($card) {
            $salesName = $card->name;
        } else {
            $invitorId = 202;
        }

        $clue            = new FeishuCallingCardFranchiseeClue;
        $clue->name      = mb_substr(trim($event->name), 0, 50);
        $clue->mobile    = mb_substr(trim($event->mobile), 0, 20);
        $clue->province  = mb_substr(trim($event->province), 0, 20);
        $clue->city      = mb_substr(trim($event->city), 0, 20);
        $clue->district  = mb_substr(trim($event->district), 0, 20);
        $clue->remark    = $remark;
        $clue->invitorId = $invitorId;
        $clue->clientIp  = $event->ip;
        $clue->save();

        $area = [];
        if (strlen($clue->province) || strlen($clue->city) || strlen($clue->district)) {
            $area = array_merge(RegionalCodeService::getCodeByAddress($clue->province, $clue->city), [
                "province" => $clue->province,
                "city"     => $clue->city,
                "district" => $clue->district,
            ]);
        } else if (strlen($remark)) {
            // 如果是区域格式:青海省-海东市-乐都区-630202
            $tmp = explode("-", $remark);
            if (count($tmp) == 4) {
                $area = [
                    "province"      => $tmp[0],
                    "city"          => $tmp[1],
                    "district"      => $tmp[2],
                    "district_code" => $tmp[3]
                ];
            } else {
                $clue->remark = mb_substr(trim($remark), 0, 255);
            }
        }

        $res = (new FreekerApi)->createClue($clue->name, $clue->mobile, $clue->invitorId, $salesName, $area, '', '夸父官网',
            $clue->remark, "表单");
        if (isset($res['data']['key']) && is_string($res['data']['key'])) {
            $clue->clueId = $res['data']['key'];
            $clue->save();
        }
    }
}
